package com.axungu.web.controller;

import com.axungu.common.Result;
import com.axungu.common.ServletContext;
import com.axungu.common.utils.DateUtil;
import com.axungu.core.modal.ssh.HostInfo;
import com.axungu.core.patchca.SimpleCaptchaService;
import com.axungu.core.service.HostInfoService;
import com.axungu.exception.NoFoundException;
import com.axungu.exception.NoLoginException;
import com.axungu.core.oauth.OauthInfo;
import com.axungu.core.oauth.OauthService;
import com.axungu.core.oauth.Permission;
import com.axungu.web.params.LoginParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author jtoms.shen
 * @version 1.0
 * @date 2018/12/7 17:38
 */
@Slf4j
@Controller
public class IndexController {

    @Autowired
    private SimpleCaptchaService simpleCaptchaService;

    @Autowired
    private OauthService oauthService;

    @Autowired
    private HostInfoService hostInfoService;

    @Value("${login.password}")
    private String loginPassword;

    @GetMapping({"/index.htm", "/"})
    public String index() {

        OauthInfo oauthInfo = this.oauthService.getOAuth();
        if (oauthInfo == null) {
            return "redirect:/login.htm";
        }
        return "index";
    }

    @Permission
    @GetMapping("/welcome.htm")
    public String welcome() {
        return "welcome";
    }

    @GetMapping("/login.htm")
    public String login(ModelMap modelMap) {
        return "login";
    }

    @ResponseBody
    @PostMapping("/login.ajax")
    public Result login(@Valid LoginParam loginParam) {

        String accessToken = ServletContext.getAccessToken();

        if (!this.simpleCaptchaService.compareCaptcha(loginParam.getCaptcha(), accessToken, true)) {
            return Result.instance("验证码输入不正确");
        }

        if (!"admin".equals(loginParam.getLoginAccount())) {
            return Result.instance("用户名或密码错误，请重新输入");
        } else {
            if (loginPassword.equals(loginParam.getLoginPassword())) {


                Date lastLoginTime = DateUtil.current();

                List<String> listAuthorities = new ArrayList<>();

                OauthInfo oauthInfo = new OauthInfo(1000L, "admin", "", lastLoginTime, accessToken, listAuthorities);
                this.oauthService.setAuth(oauthInfo);

                return Result.instance(Result.Code.SUCCESS).setData(oauthInfo);
            } else {
                return Result.instance("用户名或密码错误，请重新输入");
            }
        }
    }

    @ResponseBody
    @GetMapping("/getCaptcha.ajax")
    public Result captcha() {
        String accessToken = ServletContext.getAccessToken();

        String captcha = simpleCaptchaService.generateCaptcha(accessToken);
        if (StringUtils.isNotBlank(captcha)) {
            return Result.instance(Result.Code.SUCCESS).setData(captcha);
        } else {
            return Result.instance(Result.Code.SERVER_ERROR, "获取验证码失败");
        }
    }

    @Permission
    @RequestMapping("/terminal/{hostId:[0-9]+}/{accessToken}.htm")
    public String terminal(@PathVariable Long hostId, @PathVariable String accessToken, ModelMap modelMap) throws NoLoginException, NoFoundException {
        OauthInfo oauthInfo = this.oauthService.getOAuth();
        if (oauthInfo == null) {
            throw new NoLoginException();
        }

        HostInfo hostInfo = this.hostInfoService.findById(hostId);
        if (hostInfo == null) {
            throw new NoFoundException();
        }
        modelMap.addAttribute("hostId", hostId);
        modelMap.addAttribute("accessToken", accessToken);
        modelMap.addAttribute("hostInfo", hostInfo);
        return "terminal";
    }

    @GetMapping("/logout.htm")
    public String logout() {
        this.oauthService.destroy();
        return "redirect:/login.htm";
    }
}
